<template>
  <div>
    <el-card class="box-card" shadow="hover">
      
      <el-breadcrumb separator="/">
        <el-breadcrumb-item ><a href="https://element.eleme.io" >首页</a></el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home'}">主页</el-breadcrumb-item>
        <el-breadcrumb-item >用户管理</el-breadcrumb-item>
      </el-breadcrumb><br />

       <el-row :gutter="20">
         <el-col :span="9">
            <!-- 3.定义搜索框 -->
            <el-input placeholder="搜索用户" v-model="queryInfo.query" >
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
         </el-col>
         <el-col :span="4">
         <el-button type="primary" icon="el-icon-edit" @click="dialogVisible=true">添加用户</el-button>
         </el-col>
       </el-row><br />

       <el-table :data="userList"  stripe >
           <el-table-column type="index" label="序号" width="70px"></el-table-column>
           <el-table-column prop="name" label="用户名" align="center"></el-table-column>
           <el-table-column prop="phone" label="电话" align="center"></el-table-column>
           <el-table-column prop="createtime" label="注册时间" align="center"></el-table-column>
           <el-table-column prop="updatetime" label="修改时间" align="center"></el-table-column>
           <el-table-column label="操作" align="center">
             <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="small" @click="updateUserBtn(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUserBtn(scope.row)">删除</el-button>
             </template>
           </el-table-column>
       </el-table>
           
        <el-pagination
             background
             @size-change="handleSizeChange"
             @current-change="handleCurrentChange"
             :current-page="queryInfo.pageNum"
             :page-sizes="[10, 15, 20]"
             :page-size="queryInfo.pageSize"
             layout="total, sizes, prev, pager, next, jumper"
             :total="total">
        </el-pagination>  

    </el-card>

    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="closeDialog" :modal-append-to-body="false">
      <el-form :model="addUserModel" :rules="rules" ref="addUserRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addUserModel.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserModel.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="password2">
          <el-input v-model="addUserModel.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addUserModel.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserBtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="updateDialogVisible" width="30%" @close="closeDialog" :modal-append-to-body="false">
      <el-form :model="updateUserModel" :rules="rules" ref="updateUserRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="updateUserModel.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="updateUserModel.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>

  export default {
    data(){
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[34578][0-9]{9}$/
        if (phoneRege.test(value)) {
          return callback()
        }
        callback(new Error('请填写正确的手机号'))
      }

      const checkPassword = (rule, value, callback) => {
        if(this.addUserModel.password !== value) return callback(new Error('2次密码输入不一致'))
        //否则校验成功
        callback()
      }

      return {
        textarea: '',
        queryInfo: {
          query: '',
          pageNum: 1,
          pageSize: 10
        },
        userList: [],
        //记录总数是数值类型
        total: 0,
        dialogVisible: false,
        updateDialogVisible: false,
        addUserModel: {
          id:"",
          name:"",
          phone:"",
          password:"",
          password2:""
        },
        updateUserModel:{

        },
        rules: {
          name: [
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { min: 1, max: 5, message: '长度在1到5个字符', trigger: 'blur' }
                ],
          password: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, max: 10, message: '长度在6到10个字符', trigger: 'blur' }
                ],
          password2: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, max: 10, message: '长度在6到10个字符', trigger: 'blur' },
                  { validator: checkPassword , trigger: 'blur' }
                ],
          phone: [
                  { required: true, message: '请输入手机号', trigger: 'blur' },
                  { min: 11, max: 11, message: '长度为11个字符', trigger: 'blur' },
                  { validator: checkPhone , trigger: 'blur' }
                ]
         
        }
      }
    },
    methods: {
      async getUserList(){
        const {data: result} = await this.$http.get('/user/find',{
           params: this.queryInfo
        })
        if(result.status !== 200) return this.$message.error("用户列表查询失败")
        this.$message.success("用户列表查询成功")
        this.userList = result.data.rows
        this.total = result.data.total
        this.queryInfo.content={}
      },

      handleSizeChange(pageSize){
        //console.log("每页展现的条数"+pageSize)
        this.queryInfo.pageSize = pageSize
        this.getUserList()
      },
      handleCurrentChange(pageNum){
        //console.log("页数:"+pageNum)
        this.queryInfo.pageNum = pageNum
        this.getUserList()
      },

      closeDialog(){
        //重置表格数据
        this.$refs.addUserRef.resetFields()
        this.$refs.updateUserRef.resetFields()
      },

      async deleteUserBtn(userList){
         //1.消息确认框
         const result =  await this.$confirm('确定删除用户'+userList.name+'吗?', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
                 }).catch(error => error)

         //如果确认  confirm  如果取消 cancel
         if(result !== 'confirm'){
            return this.$message.info("删除取消")
         }
         const {data: result2} = await this.$http.delete(`/user/${userList.id}`)
         if(result2.status !== 200) return this.$message.error("删除失败")
         this.$message.success("删除成功")
         //重新加载 数据
         this.getUserList()
      },

      async addUserBtn(){
        this.$refs.addUserRef.validate(async valid => {
          //如果校验失败 则停止数据
          if(!valid)  return
          const {data: result} = await this.$http.post('/user/addUser',this.addUserModel)
          if(result.status !== 200) return this.$message.error("添加用户失败")
          this.$message.success("添加用户成功")
          //关闭对话框
          this.dialogVisible = false
          //重新获取用户列表
          this.getUserList()
        })
    },

      async updateUserBtn(user){
        this.updateDialogVisible=true;
        const {data: result} = await this.$http.get("/user/"+user.id)
        if(result.status !== 200) return this.$message.error("用户查询失败")
        this.updateUserModel = result.data
    },

      updateUser(){
        //1.预校验数据
        this.$refs.updateUserRef.validate(async valid => {
           if(!valid)  return this.$message.error("表单验证没有通过")
           //根据接口文档要求封装数据
           let user = {}
           user.id = this.updateUserModel.id
           user.name = this.updateUserModel.name
           user.phone = this.updateUserModel.phone
           const {data: result} = await this.$http.put(`/user/updateUser`,user)
           if(result.status !== 200) return this.$message.error("用户修改失败")
           this.$message.success("用户更新成功")
           this.updateDialogVisible = false
           this.getUserList()
        })
      }
  },
  //利用钩子函数实现数据查询
    mounted(){
      this.getUserList()
    }
  }
</script>


<style lang="less" scoped>
  .el-pagination {
      text-align: center;
  }
</style>
